"""Local Pooled Error

.. helpdoc::


"""

"""<widgetXML>
<name>Local Pooled Error</name>
    <icon>Default.png</icon>
    <tags> 
        <tag>Microarray</tag> 
    </tags>
    <summary></summary>
    <author>
        <authorname>Kyle R Covington</authorname>
        <authorcontact>kyle@red-r.org</authorcontact>
    </author>
</widgetXML>
"""

"""
<name>Local Pooled Error</name>
<author>Generated using Widget Maker written by Kyle R. Covington</author>
<description></description>
<RFunctions>LPE:lpe</RFunctions>
<tags>Microarray</tags>
<icon></icon>
"""
from OWRpy import * 
from libraries.base.qtWidgets.lineEdit import lineEdit as redRlineEdit 
from libraries.base.qtWidgets.radioButtons import radioButtons as redRradioButtons 
from libraries.base.qtWidgets.comboBox import comboBox as redRcomboBox 
from libraries.base.qtWidgets.checkBox import checkBox as redRcheckBox 
from libraries.base.qtWidgets.textEdit import textEdit as redRtextEdit 
from libraries.base.qtWidgets.listBox import listBox as redRlistBox
from libraries.base.qtWidgets.spinBox import spinBox as redRspinBox
import libraries.base.signalClasses as signals

class RedRlpe(OWRpy): 
    settingsList = []
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.require_librarys(["LPE"])
        
        self.setRvariableNames(["lpe", 'baseOligA', 'baseOligB'])
        self.data = {}
        self.RFunctionParam_data = ''
        
        """.. rrsignals::"""
        self.inputs.addInput("data", "Expression Data", signals.RDataFrame.RDataFrame, self.processdata)
        
        """.. rrsignals::"""
        self.outputs.addOutput("lpe Output","lpe Output", signals.RDataFrame.RDataFrame)
        
        # self.RFunctionParamprobe_set_name_lineEdit = redRlineEdit(self.controlArea, label = "probe_set_name:", text = 'NULL')
        # self.RFunctionParambasevar_x_lineEdit = redRlineEdit(self.controlArea, label = "basevar_x:", text = '')
        # self.RFunctionParambasevar_y_lineEdit = redRlineEdit(self.controlArea, label = "basevar_y:", text = '')
        wb = redRwidgetBox(self.controlArea, orientation = 'horizontal')
        
        
        """.. rrgui::"""
        self.typeA = redRlistBox(wb, label = 'Class A Samples')
        self.typeA.setSelectionMode(QAbstractItemView.ExtendedSelection)
        
        """.. rrgui::"""
        self.typeB = redRlistBox(wb, label = 'Class B Samples')
        self.typeB.setSelectionMode(QAbstractItemView.ExtendedSelection)
        
        """.. rrgui::"""
        self.statsCombo = redRcomboBox(self.controlArea, label = 'Binning Stat:', items = ['median', 'mean'])
        
        """.. rrgui::"""
        self.quantiles = redRspinBox(self.controlArea, label = 'Bins:', min = 1, value = 100)
        
        """.. rrgui::"""
        self.min_genes_int = redRspinBox(self.controlArea, label = 'Minimum Genes Interval:', min = 1, value = 10)
        
        """.. rrgui::"""
        self.division_Factor = redRlineEdit(self.controlArea, label = 'Minimum Division Factor:', text = '1')
        
        """.. rrgui::"""
        self.RFunctionParamdf_lineEdit = redRlineEdit(self.controlArea, label = "Degrees of Freedom:", text = '10')
        
        """.. rrgui::"""
        self.RFunctionParamtrim_percent_lineEdit = redRlineEdit(self.controlArea, label = "trim_percent:", text = '5')
        
        #self.RFunctionParamy_lineEdit = redRlineEdit(self.controlArea, label = "y:", text = '')
        
        """.. rrgui::"""
        self.RFunctionParamarray_type_lineEdit = redRcomboBox(self.controlArea, label = "Arrya Type:", items = ['"olig"'])
        #self.RFunctionParamx_lineEdit = redRlineEdit(self.controlArea, label = "x:", text = '')
        
        """.. rrgui::"""
        redRCommitButton(self.bottomAreaRight, "Commit", callback = self.commitFunction)
        
        """.. rrgui::"""
        self.RoutputWindow = redRtextEdit(self.controlArea, label = "R Output Window")
    def processdata(self, data):
        
        if data:
            self.RFunctionParam_data=data.getData()
            #self.data = data
            names = self.R('names('+self.RFunctionParam_data+')', wantType = 'list')
            self.typeA.update(names)
            self.typeB.update(names)
            self.commitFunction()
        else:
            self.RFunctionParam_data=''
    def commitFunction(self):
        if unicode(self.RFunctionParam_data) == '': return
        self.RoutputWindow.clear()
        ## we need to do several things here.  First, we need to make the baseOlig.error values for each of the classes of data that are selected.
        ### collect the names of the samples for type A and type B
        tA = [unicode(i.text()) for i in self.typeA.selectedItems()]
        tB = [unicode(i.text()) for i in self.typeB.selectedItems()]
        for i in tA:
            if i in tB:
                self.status.setText('Same sample, %s, selected in both class A and class B' % i)
                return
        ## make the baseOlig.error objects for A and B
        try:
            int(self.division_Factor.text())
        except:
            self.status.setText('Division Factor is not an integer')
            return
        self.R('%s<-baseOlig.error(%s[,c("%s")], q = 1/%s, stats = %s, min.genes.int = %s, div.factor = %s)' % (self.Rvariables['baseOligA'], self.RFunctionParam_data, '","'.join(tA), unicode(self.quantiles.value()), self.statsCombo.currentText(), unicode(self.min_genes_int.value()), unicode(self.division_Factor.text())), wantType = 'NoConversion') 
        self.R('%s<-baseOlig.error(%s[,c("%s")], q = 1/%s, stats = %s, min.genes.int = %s, div.factor = %s)' % (self.Rvariables['baseOligB'], self.RFunctionParam_data, '","'.join(tB), unicode(self.quantiles.value()), self.statsCombo.currentText(), unicode(self.min_genes_int.value()), unicode(self.division_Factor.text())), wantType = 'NoConversion') 
        injection = []
        string = 'probe.set.name='+'rownames(%s)' % self.RFunctionParam_data+''
        injection.append(string)
        string = 'basevar.x='+self.Rvariables['baseOligA']+''
        injection.append(string)
        string = 'basevar.y='+self.Rvariables['baseOligB']+''
        injection.append(string)
        if unicode(self.RFunctionParamdf_lineEdit.text()) != '':
            string = 'df='+unicode(self.RFunctionParamdf_lineEdit.text())+''
            injection.append(string)
        if unicode(self.RFunctionParamtrim_percent_lineEdit.text()) != '':
            string = 'trim.percent='+unicode(self.RFunctionParamtrim_percent_lineEdit.text())+''
            injection.append(string)
        string = 'y=%s[,c("%s")]' % (self.RFunctionParam_data, '","'.join(tB))
        injection.append(string)
        string = 'array.type='+unicode(self.RFunctionParamarray_type_lineEdit.currentText())+''
        injection.append(string)
        string = 'x=%s[c("%s")]' % (self.RFunctionParam_data, '","'.join(tA))
        injection.append(string)
        inj = ','.join(injection)
        self.R(self.Rvariables['lpe']+'<-data.frame(lpe('+inj+'))')
        output = self.R('capture.output(summary('+self.Rvariables['lpe']+'))', wantType = 'list')
        self.RoutputWindow.insertPlainText('\n'.join(output))
        newData = signals.RDataFrame.RDataFrame(self, data = self.Rvariables['lpe'])
        self.rSend('lpe Output', newData)